<template>
  <div class="container">
      <el-container>
        <el-header class="query-container">
          <div class="query-box">
            <el-row class="row-bg" justify="space-evenly">
              <el-col :span="6"><div class="grid-content ep-bg-purple" />
                文件名 &nbsp; <el-input v-model="fileNameValue" style="width: 240px" placeholder="请输入文件名" />
              </el-col>
              <el-col :span="6"><div class="grid-content ep-bg-purple" />
                <el-button type="primary" @click="queryFile()">查询</el-button>
              </el-col>
            </el-row>
          </div>
        </el-header>
        <el-divider />
        <el-main class="main-container">
          <el-table :data="fileInfoList" style="width: 100%" :scrollbar-always-on="false" v-loading="fileTableLoading">
            <el-table-column fixed prop="number" label="序号" width="100" />
            <el-table-column prop="user.userName" label="用户名" width="180" />
            <el-table-column prop="originalFilename" label="文件名"  width="200"/>
            <el-table-column prop="chartVO.name" label="图表名"  width="230"/>
            <el-table-column prop="integral" label="消耗调用次数"  width="200"/>
            <el-table-column prop="createTime" label="创建时间"  width="220"/>
<!--            tod 根据权限判断-->
            <el-table-column fixed="right" label="操作" >
              <template #default="scope">
                <el-button
                    size="small"
                    type="danger"
                    @click="deleteFile(scope.row.id)"
                >删除</el-button>
                <el-button type="primary" size="small" @click="downloadFile(scope.row.id)">下载</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-main>
      </el-container>
      <div class="pagination-container">
        <el-pagination
            :page-size="pageSize"
            layout="prev, pager, next"
            :total="totalRow"
            v-model:current-page="currentPage"
            @current-change="handleCurrentChange"
        />
      </div>
  </div>
</template>
<!--文件列表-->
<script setup>
import {onMounted, ref} from "vue";
import {useRouter} from "vue-router";
import myAxios from "../../../plugins/myAxios.js";
import {ElMessage} from "element-plus";
import axios from "axios";

const router = useRouter();

const currentPage = ref(1);  //当前页
const totalRow = ref(0); //总页数
const pageSize = ref(10); //当前显示条数

const fileTableLoading = ref(true);
const fileNameValue = ref('')
const fileInfoList = ref([
]);


onMounted(() =>{
  queryFile();
})

const queryFile = () => {
  fileTableLoading.value = true;
  getFileInfoList();
}

/**
 * 分页查询
 * @param currentPageNumber
 */
const handleCurrentChange = (currentPageNumber) => {
  console.log(`current page: ${currentPageNumber}`)
  fileTableLoading.value = true;
  currentPage.value = currentPageNumber;
  getFileInfoList()
}

/**
 * 查询
 * @returns {Promise<void>}
 */
const getFileInfoList = async () => {
  const res = await myAxios.post('/file/list/page',{
    current:currentPage.value,
    pageSize:pageSize.value,
    fileName:fileNameValue.value
  }).catch((e) => {
    console.log(e)
    fileTableLoading.value = false;
    ElMessage.error("系统错误")
  });
  if(res.code  === 40100 && res.message === '未登录'){
    fileTableLoading.value = false;
    router.push({path: '/login', replace: true});
    ElMessage.error("用户未登录")
    return ;
  }
  if (res.code === 2001 && res.data) {
    fileInfoList.value = res.data;
    for (let i = 0; i < fileInfoList.value.length; i++) {
      let createTime = fileInfoList.value[i].createTime;
      const date = new Date(createTime);
// 获取具体的时间形式
      const year = date.getFullYear();
      const month = date.getMonth() + 1; // 月份从 0 开始，需要加 1
      const day = date.getDate();
      const hours = date.getHours();
      const minutes = date.getMinutes();
      const seconds = date.getSeconds();
// 格式化输出
      fileInfoList.value[i].createTime = `${year}-${month < 10 ? '0' : ''}${month}-${day < 10 ? '0' : ''}${day} ${hours}:${minutes}:${seconds}`;
    }
    currentPage.value = res.current;
    pageSize.value = res.pageSize;
    totalRow.value = res.total;
  }else if(res.code === 50000){
    ElMessage.error(res.message);
  } else {
    ElMessage.error("系统错误")
  }
  fileTableLoading.value = false;
}

/**
 * 删除文件
 * @param sourceFileId
 * @returns {Promise<void>}
 */
const deleteFile = async (sourceFileId) => {
  const res = await myAxios.post('/file/delete',{
    id:sourceFileId
  }).catch(() => {
    console.log(e)
    fileTableLoading.value = false;
    ElMessage.error("系统错误")
  });
  if(res.code  === 40100 && res.message === '未登录'){
    fileTableLoading.value = false;
    router.push({path: '/login', replace: true});
    ElMessage.error("用户未登录")
    return ;
  }
  if (res.code === 0) {
    ElMessage.success("删除成功")
    new Promise(() => {
      getFileInfoList();
      fileTableLoading.value = false;
    })
  }else if(res.code === 50000){
    ElMessage.error(res.message);
  } else {
    ElMessage.error("系统错误")
  }
  fileTableLoading.value = false;
}

/**
 * 文件下载
 * @param sourceFileId
 */
const downloadFile = async (sourceFileId) => {
  axios.post("http://localhost:8101/api/file/download" ,
      {id:sourceFileId},
      {headers:{
      'Access-Control-Allow-Origin':"*",
      }, responseType:'blob'})
      .then((res) => {
    console.log(res);
    const blob = new Blob([res.data])//返回一个新的blob对象
    console.log(blob);
    let fileName = decodeURIComponent(
        res.headers['content-disposition'].split('=')[1].replace("utf-8''", '')
    )
    console.log(fileName);
    let fileReader = new FileReader()
    fileReader.readAsDataURL(blob)
    fileReader.onload = (e) => {
      const link = document.createElement('a')
      const url = URL.createObjectURL(blob)
      link.href = url
      link.download = fileName
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)
    }
    // let fileName = '模版.xls'//下载文件名
    // const downLoadElement = document.createElement('a')//创建a标签
    // downLoadElement.style.display = 'none'//a标签样式为隐藏
    // const href = window.URL.createObjectURL(blob)//创建window临时地址
    // downLoadElement.href = href//跳转地址
    // downLoadElement.setAttribute('download', fileName)
    // document.body.appendChild(downLoadElement)//将指定的dom添加的body之后
    // downLoadElement.click()//点击事件
    // document.body.removeChild(downLoadElement)//移除dom
    // window.URL.revokeObjectURL(href)//释放url地址
  })
    // myAxios.get("http://localhost:8101/api/file/download?id=" +sourceFileId,{headers:{
    //     'Access-Control-Allow-Origin':"*"
    //   }} )

  // 原生请求可替换成对应封装后请求成功的回调中进行处理
  //   axios.post("http://localhost:8101/api/file/download",
  //       {id:sourceFileId})
  //       .then((res) => {
  //         console.log(res);
  //         // const blob = new Blob([res.data])//返回一个新的blob对象
  //         // let fileName = '模版.xls'//下载文件名
  //         // const downLoadElement = document.createElement('a')//创建a标签
  //         // downLoadElement.style.display = 'none'//a标签样式为隐藏
  //         // const href = window.URL.createObjectURL(blob)//创建window临时地址
  //         // downLoadElement.href = href//跳转地址
  //         // downLoadElement.setAttribute('download', fileName)
  //         // document.body.appendChild(downLoadElement)//将指定的dom添加的body之后
  //         // downLoadElement.click()//点击事件
  //         // document.body.removeChild(downLoadElement)//移除dom
  //         // window.URL.revokeObjectURL(href)//释放url地址
  //       }).catch((err) => {
  //     console.log(err);
  // });
  // const res = await myAxios.post('/file/download',{
  //   id:sourceFileId
  // },{
  //   headers: {
  //     'X-Requested-With': 'XMLHttpRequest'
  //   },
  //   responseType: 'blob'
  // });
  // console.log(res);
  // let blob = new Blob([res.data])
  // let fileName = decodeURIComponent(
  //     res.headers['content-disposition'].split('=')[1].replace("utf-8''", '')
  // )
  // let fileReader = new FileReader()
  // fileReader.readAsDataURL(blob)
  // fileReader.onload = (e) => {
  //   const link = document.createElement('a')
  //   const url = URL.createObjectURL(blob)
  //   link.href = url
  //   link.download = fileName
  //   document.body.appendChild(link)
  //   link.click()
  //   document.body.removeChild(link)
  //   URL.revokeObjectURL(url)
  // }
}



</script>

<style scoped lang="less">
.query-container{
  width: 100%;
  margin:-20px 0 5px 30px;
  .query-box{

  }
}

.main-container{
  width: 100%;
  //height: 100%;
  //background: blue;
  margin-top: -35px;
  //margin-left: 50px;
  padding-left: 50px;
}

.el-row {
  margin-bottom: 20px;
}
.el-row:last-child {
  margin-bottom: 0;
}
.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.pagination-container{
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

</style>